package services

import (
	"mishop/models"
	"mishop/utils"
)

type IOrderItemService interface {
	FindByID(itemId uint) (*models.OrderItem, error)
	FindByUserID(page, rows int, userId uint) (*models.Pages, error)
	Create(c *models.OrderItem) (*models.OrderItem, error)
	Update(c *models.OrderItem) (*models.OrderItem, error)
	Delete(itemId int) error
}

type OrderItemService struct {
	model        models.IOrderItem
	orderModel   models.IOrder
	productModel models.IProduct
}

func (p *OrderItemService) Delete(itemID int) error {
	return p.model.Delete(itemID)
}

func (p *OrderItemService) Update(c *models.OrderItem) (*models.OrderItem, error) {
	//TODO 事务
	//更新orderItem
	orderItem, err := p.model.Update(c)
	if err != nil {
		return nil, err
	}
	//更新order
	orderService := NewOrderService(models.NewOrder(models.Db), models.NewOrderItem(models.Db), models.NewProduct(models.Db))
	_,err=orderService.FindByID(orderItem.OrderID)
	if err!=nil{
		return nil , err
	}
/*	for i, item := range order.OrderItems {

	}*/
	return orderItem, nil
}

func (p *OrderItemService) Create(c *models.OrderItem) (*models.OrderItem, error) {
	return p.model.Create(c)
}
func (p *OrderItemService) FindByID(itemId uint) (*models.OrderItem, error) {
	return p.model.FindByID(int(itemId))
}

func (p *OrderItemService) FindByUserID(page, rows int, userId uint) (*models.Pages, error) {
	page, rows = utils.ProcessPagesEntity(page, rows)
	return p.model.FindByUserID(page, rows, userId)
}

func NewOrderItemService(model models.IOrderItem, orderModel models.IOrder, productModel models.IProduct) IOrderItemService {
	return &OrderItemService{model: model, orderModel: orderModel, productModel: productModel}
}
